package com.adityayadav.parallelism.actors;

import com.adityayadav.parallelism.core.ThreadPool;

public abstract class StatelessFiniteProcessor<T> implements IProcessor, Cloneable {
	protected ThreadPool processorThreadPool;
	protected Mailbox<T> mailbox;
	
	public StatelessFiniteProcessor(ThreadPool processorThreadPool){
		this.processorThreadPool = processorThreadPool;
	}
	
	
	
	public Mailbox<T> getMailbox() {
		return mailbox;
	}



	public void setMailbox(Mailbox<T> mailbox) {
		this.mailbox = mailbox;
	}



	@Override
	public void commit() throws Exception {
		processorThreadPool.addTask(this);
	}

	@Override
	public void initialize() throws Exception {
		
		
	}

	@Override
	public void rollback() throws Exception {
		processorThreadPool.addTask(this);		
	}

	@Override
	public void run() throws Exception {
		T task = mailbox.peek();
		if (task != null){
			task = mailbox.take();
			process(task);
		}
	}

	public abstract void process(Object task) throws Exception;
	
	public Object clone() {
		try {
			StatelessFiniteProcessor<T> cloned = (StatelessFiniteProcessor<T>) super
					.clone();
			cloned.processorThreadPool = this.processorThreadPool;
			cloned.mailbox = this.mailbox;
			return cloned;
		} catch (CloneNotSupportedException e) {
			return null;
		}
	}
}
